package com.example.drugs1.controllers;

import com.example.drugs1.dao.UserAccountRepository;
import com.example.drugs1.entities.User;
import com.example.drugs1.mapper.UserMapper;
import com.example.drugs1.services.UserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class PersionController {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAccountService userAccountService;
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    UserAccountRepository userAccountRepository;

    @RequestMapping("/login")

    public String login(){

        return "login/login";
    }


    @GetMapping("/register")
    public String register(Model model){
        User user =new User();
        model.addAttribute("user1", user);
        return "security/register";
    }

    @PostMapping("/register/save")
    public String saveUser(User user){
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        userAccountRepository.save(user);
        return "redirect:/";
    }

    @RequestMapping("/updateUser")
    public String updateUser(Model model){
        Authentication authentication=SecurityContextHolder.getContext().getAuthentication();
        if ("anonymousUser".equals(authentication.getName())){
            model.addAttribute("name","未登录");
        }else {
            model.addAttribute("name",authentication.getName());
        }
        return "persion/updateUser";
    }
    @RequestMapping("/updateUser/pw")
    public String updateUserPw(@RequestParam("username") String username, @RequestParam("password")String password,@RequestParam("password1")String password1,Model model){
        int a=userAccountService.UpdateUser(username,password,password1);
        if(a==2) {
            return "redirect:/logout";
        }else if(a==1){
            model.addAttribute("error","错误：原密码错误/未输入原密码");
            return "persion/updateUser";
        }else if (a==0){
            model.addAttribute("error","错误：账户不存在/未输入账户");
            return "persion/updateUser";
        }else if (a==3){
            model.addAttribute("error","错误：新密码不可为空");
            return "persion/updateUser";
        }
        return null;
    }
    @RequestMapping("/open403")
    public  String open403(){
        return "login/403";
    }

}
